﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace YJKRevitBase.StringUtility
{
	internal class AesCoder : IStrCoder, IEnCoder
	{
		internal AesCoder(string inputKey = null)
		{
			if (!string.IsNullOrWhiteSpace(inputKey))
			{
				this.m_strUseKeyString = inputKey;
			}
		}

		private byte[] GetKeyByte(string inputKey, int number)
		{
			if (string.IsNullOrWhiteSpace(inputKey))
			{
				throw new ArgumentException();
			}
			if (inputKey.Length < number)
			{
				inputKey = inputKey.PadRight(this.m_useByteNumber, this.m_paddingChar);
			}
			else
			{
				inputKey = inputKey.Substring(0, number);
			}
			byte[] array = Encoding.UTF8.GetBytes(inputKey);
			if (array.Length > number)
			{
				List<byte> list = new List<byte>();
				for (int i = 0; i < number; i++)
				{
					list.Add(array[i]);
				}
				array = list.ToArray();
			}
			return array;
		}

		public string DeCode(string input)
		{
			string result;
			using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider())
			{
				this.PrepareProvider(aesCryptoServiceProvider);
				using (ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateDecryptor())
				{
					try
					{
						byte[] array = Convert.FromBase64String(input);
						byte[] bytes = cryptoTransform.TransformFinalBlock(array, 0, array.Length);
						aesCryptoServiceProvider.Clear();
						result = Encoding.UTF8.GetString(bytes);
					}
					catch (Exception)
					{
						result = string.Empty;
					}
				}
			}
			return result;
		}

		private void PrepareProvider(AesCryptoServiceProvider useProvider)
		{
			useProvider.Key = this.GetKeyByte(this.m_strUseKeyString, this.m_useByteNumber);
			useProvider.Mode = CipherMode.CBC;
			useProvider.Padding = PaddingMode.PKCS7;
			useProvider.IV = this.GetKeyByte(this.m_strIVUseKeyString, (int)(0.5 * (double)this.m_useByteNumber));
		}

		public string EnCode(string input)
		{
			string result;
			using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider())
			{
				this.PrepareProvider(aesCryptoServiceProvider);
				using (ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateEncryptor())
				{
					byte[] bytes = Encoding.UTF8.GetBytes(input);
					byte[] inArray = cryptoTransform.TransformFinalBlock(bytes, 0, bytes.Length);
					aesCryptoServiceProvider.Clear();
					result = Convert.ToBase64String(inArray);
				}
			}
			return result;
		}

		private string m_strUseKeyString = "HY";

		private string m_strIVUseKeyString = "181121";

		private int m_useByteNumber = 32;

		private char m_paddingChar = 'a';
	}
}
